<template>
  <div class="cart-container">
    <div class="cart-header">
      <h1 class="page-title">我的购物车</h1>
      <div class="cart-steps">
        <el-steps :active="1" simple>
          <el-step title="确认购物车" icon="ShoppingCart" />
          <el-step title="确认订单" icon="Document" />
          <el-step title="支付" icon="CreditCard" />
          <el-step title="完成" icon="CircleCheck" />
        </el-steps>
      </div>
    </div>

    <!-- 购物车为空 -->
    <el-empty 
      v-if="!loading && (!cartItems || cartItems.length === 0)" 
      description="购物车空空如也，快去选购商品吧~"
    >
      <el-button type="primary" @click="goToShop">去购物</el-button>
    </el-empty>

    <!-- 购物车列表 -->
    <div v-else-if="!loading" class="cart-main">
      <div class="cart-table">
        <div class="cart-table-header">
          <el-checkbox v-model="allSelected" @change="handleSelectAllChange">全选</el-checkbox>
          <span class="item-label">商品信息</span>
          <span class="item-price">单价</span>
          <span class="item-quantity">数量</span>
          <span class="item-total">小计</span>
          <span class="item-action">操作</span>
        </div>
        
        <div class="cart-items">
          <div 
            v-for="item in cartItems" 
            :key="item.id" 
            class="cart-item"
            :class="{ 'item-out-of-store': item.store <= 0 }"
          >
            <div class="item-check">
              <el-checkbox 
                v-model="item.selected" 
                @change="handleItemSelectChange" 
                :disabled="item.store <= 0"
              />
            </div>
            
            <div class="item-info">
              <div class="item-image" @click="goToProduct(item.productId)">
                <el-image :src="item.cover || defaultImage" fit="cover" />
              </div>
              <div class="item-details">
                <div class="item-title" @click="goToProduct(item.productId)">{{ item.title }}</div>
                <div class="item-spec" v-if="item.specName">规格：{{ item.specName }}</div>
                <div class="item-status" v-if="item.store <= 0">已售罄</div>
              </div>
            </div>
            
            <div class="item-price">
              <span class="price">¥{{ item.price.toFixed(2) }}</span>
            </div>
            
            <div class="item-quantity">
              <el-input-number 
                v-model="item.quantity" 
                :min="1" 
                :max="Math.max(1, item.store || 1)" 
                :disabled="item.store <= 0"
                @change="(val) => handleQuantityChange(item, val)"
              />
            </div>
            
            <div class="item-total">
              <span class="price total">¥{{ (item.price * item.quantity).toFixed(2) }}</span>
            </div>
            
            <div class="item-action">
              <el-popconfirm 
                title="确定从购物车中移除该商品?" 
                @confirm="removeFromCart(item.id)"
              >
                <template #reference>
                  <el-button type="danger" plain size="small">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </div>
        </div>
      </div>
      
      <div class="cart-footer">
        <div class="cart-footer-left">
          <el-checkbox v-model="allSelected" @change="handleSelectAllChange">全选</el-checkbox>
          <el-button size="small" @click="handleBatchDelete" :disabled="!hasSelectedItems">
            批量删除
          </el-button>
          <el-button size="small" @click="clearCart" type="danger" plain>
            清空购物车
          </el-button>
        </div>
        
        <div class="cart-footer-right">
          <div class="selected-count">
            已选 <span class="highlight">{{ selectedCount }}</span> 件商品
          </div>
          <div class="total-price">
            合计: <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
          </div>
          <el-button 
            type="primary" 
            size="large" 
            :disabled="!hasSelectedItems"
            @click="checkout"
          >
            去结算
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-else class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 推荐商品 -->
    <div class="recommended-products" v-if="recommendedProducts.length > 0">
      <h2 class="section-title">猜你喜欢</h2>
      <div class="product-list">
        <div v-for="product in recommendedProducts" :key="product.id" class="product-item">
          <div class="product-card" @click="goToProduct(product.id)">
            <div class="product-img">
              <el-image :src="product.cover || defaultImage" fit="cover" />
            </div>
            <div class="product-info">
              <div class="product-title">{{ product.title }}</div>
              <div class="product-price">¥{{ product.price.toFixed(2) }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserWebCart'
}
</script>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/utils/request';

const router = useRouter();
const loading = ref(true);
const cartItems = ref([]);
const allSelected = ref(false);
const defaultImage = ''; // 内联Base64编码的默认图片
const recommendedProducts = ref([]);
const baseUrl = 'http://localhost:9191'; // 添加后端服务器基础URL

// 选中的商品数量
const selectedCount = computed(() => {
  return cartItems.value.filter(item => item.selected && item.store > 0).length;
});

// 是否有选中的商品
const hasSelectedItems = computed(() => {
  return selectedCount.value > 0;
});

// 总价
const totalPrice = computed(() => {
  return cartItems.value
    .filter(item => item.selected && item.store > 0)
    .reduce((total, item) => total + item.price * item.quantity, 0);
});

// 处理图片URL的函数
const getImageUrl = (imgPath) => {
  if (!imgPath) return defaultImage;
  
  // 如果路径以http或https开头，说明是完整的URL，直接返回
  if (imgPath.startsWith('http://') || imgPath.startsWith('https://')) {
    return imgPath;
  }
  
  // 如果路径以/file/开头，需要拼接后端服务器地址
  if (imgPath.startsWith('/file/')) {
    return `${baseUrl}${imgPath}`;
  }
  
  // 其他情况直接拼接
  return `${baseUrl}/file/${imgPath}`;
};

// 获取购物车数据
const fetchCartData = async () => {
  loading.value = true;
  try {
    // 从sessionStorage获取用户信息
    const userStr = sessionStorage.getItem('user');
    if (!userStr) {
      ElMessage.warning('请先登录');
      router.push('/login');
      return;
    }
    const user = JSON.parse(userStr);
    
    // 调用后端接口获取购物车数据
    const response = await request.get(`/api/cart/userid/${user.id}`);
    if (response && response.code === '200') {
      // 处理购物车数据
      cartItems.value = (response.data || []).map(item => ({
        id: item.id,
        productId: item.goodId,
        title: item.goodName || '未知商品',
        cover: getImageUrl(item.img),
        price: item.price || 0,
        specName: item.standard || '',
        quantity: Math.max(1, item.count || 1),
        store: Math.max(0, item.store || 0),
        selected: false
      }));
    } else {
      ElMessage.error(response.msg || '获取购物车数据失败');
      cartItems.value = [];
    }
  } catch (error) {
    console.error('获取购物车数据失败:', error);
    ElMessage.error('获取购物车数据失败，请稍后再试');
    cartItems.value = [];
  } finally {
    loading.value = false;
  }
};

// 获取推荐商品
const fetchRecommendedProducts = () => {
  try {
    // 模拟数据
    recommendedProducts.value = Array(4).fill().map((_, index) => ({
      id: 100 + index,
      title: `推荐商品 ${index + 1}`,
      cover: `https://picsum.photos/id/${70 + index}/300/300`,
      price: Math.floor(Math.random() * 9000) + 1000
    }));
  } catch (error) {
    console.error('获取推荐商品失败:', error);
    recommendedProducts.value = [];
  }
};

// 全选/取消全选
const handleSelectAllChange = (val) => {
  cartItems.value.forEach(item => {
    if (item.store > 0) {
      item.selected = val;
    }
  });
};

// 单个商品选择变化
const handleItemSelectChange = () => {
  const availableItems = cartItems.value.filter(item => item.store > 0);
  allSelected.value = availableItems.length > 0 && availableItems.every(item => item.selected);
};

// 修改商品数量
const handleQuantityChange = async (item, newQuantity) => {
  try {
    // 确保数量在有效范围内
    const validQuantity = Math.min(Math.max(1, newQuantity), Math.max(1, item.store || 1));
    
    const response = await request.put('/api/cart', {
      id: item.id,
      count: validQuantity
    });
    
    if (response && response.code === '200') {
      item.quantity = validQuantity;
      ElMessage.success('修改数量成功');
    } else {
      ElMessage.error(response.msg || '修改数量失败');
      // 恢复原来的数量
      item.quantity = Math.max(1, item.quantity);
    }
  } catch (error) {
    console.error('修改商品数量失败:', error);
    ElMessage.error('修改商品数量失败，请稍后再试');
    // 恢复原来的数量
    item.quantity = Math.max(1, item.quantity);
  }
};

// 从购物车中移除商品
const removeFromCart = async (itemId) => {
  try {
    const response = await request.delete(`/api/cart/${itemId}`);
    if (response && response.code === '200') {
      cartItems.value = cartItems.value.filter(item => item.id !== itemId);
      ElMessage.success('已从购物车中移除商品');
    } else {
      ElMessage.error(response.msg || '移除商品失败');
    }
  } catch (error) {
    console.error('移除商品失败:', error);
    ElMessage.error('移除商品失败，请稍后再试');
  }
};

// 批量删除选中商品
const handleBatchDelete = () => {
  if (!hasSelectedItems.value) return;
  
  ElMessageBox.confirm('确定要删除选中的商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const selectedIds = cartItems.value
        .filter(item => item.selected)
        .map(item => item.id);
      
      // 逐个删除选中的商品
      for (const id of selectedIds) {
        await request.delete(`/api/cart/${id}`);
      }
      
      cartItems.value = cartItems.value.filter(item => !item.selected);
      ElMessage.success('已删除选中商品');
    } catch (error) {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败，请稍后再试');
    }
  }).catch(() => {});
};

// 清空购物车
const clearCart = () => {
  ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 获取所有购物车项的ID
      const allIds = cartItems.value.map(item => item.id);
      
      // 逐个删除购物车项
      for (const id of allIds) {
        await request.delete(`/api/cart/${id}`);
      }
      
      cartItems.value = [];
      ElMessage.success('已清空购物车');
    } catch (error) {
      console.error('清空购物车失败:', error);
      ElMessage.error('清空购物车失败，请稍后再试');
    }
  }).catch(() => {});
};

// 去结算
const checkout = () => {
  if (!hasSelectedItems.value) return;
  
  try {
    // 获取选中的商品数据
    const selectedItems = cartItems.value.filter(item => item.selected && item.store > 0);
    
    // 将选中的商品保存到sessionStorage，供订单页面使用
    sessionStorage.setItem('selectedItems', JSON.stringify(selectedItems));
    
    // 跳转到订单确认页面
    router.push('/userWeb/orders');
  } catch (error) {
    console.error('处理结算数据失败:', error);
    ElMessage.error('结算失败，请稍后再试');
  }
};

// 跳转到商品详情
const goToProduct = (productId) => {
  router.push(`/userWeb/product/${productId}`);
};

// 前往购物
const goToShop = () => {
  router.push('/userWeb/index');
};

// 监听购物车数据变化，更新全选状态
watch(cartItems, () => {
  const availableItems = cartItems.value.filter(item => item.store > 0);
  allSelected.value = availableItems.length > 0 && availableItems.every(item => item.selected);
}, { deep: true });

onMounted(() => {
  fetchCartData();
  fetchRecommendedProducts();
});
</script>

<style scoped>
.cart-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.cart-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 24px;
  margin: 0 0 20px;
  color: #333;
}

.cart-steps {
  margin-bottom: 20px;
}

.loading-container {
  padding: 30px 0;
}

/* 购物车表格样式 */
.cart-table {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 20px;
}

.cart-table-header {
  display: grid;
  grid-template-columns: 60px 450px 150px 150px 150px 100px;
  background-color: #f5f7fa;
  padding: 15px;
  font-weight: bold;
  text-align: center;
}

.cart-table-header .item-label {
  text-align: left;
  padding-left: 110px;
}

.cart-items {
  background-color: #fff;
}

.cart-item {
  display: grid;
  grid-template-columns: 60px 450px 150px 150px 150px 100px;
  padding: 15px;
  border-top: 1px solid #ebeef5;
  align-items: center;
  text-align: center;
}

.item-out-of-store {
  opacity: 0.7;
}

.item-info {
  display: flex;
  align-items: center;
  text-align: left;
}

.item-image {
  width: 100px;
  height: 100px;
  overflow: hidden;
  margin-right: 10px;
  cursor: pointer;
  border: 1px solid #eee;
}

.item-image .el-image {
  width: 100%;
  height: 100%;
}

.item-details {
  flex: 1;
}

.item-title {
  font-size: 14px;
  margin-bottom: 8px;
  cursor: pointer;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-title:hover {
  color: #409EFF;
}

.item-spec {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.item-status {
  color: #ff4d4f;
  font-size: 12px;
}

.price {
  color: #ff4d4f;
  font-weight: bold;
}

.total {
  font-size: 16px;
}

/* 购物车底部 */
.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #f7f7f7;
  border-radius: 4px;
}

.cart-footer-left {
  display: flex;
  align-items: center;
}

.cart-footer-left .el-checkbox {
  margin-right: 15px;
}

.cart-footer-left .el-button {
  margin-right: 10px;
}

.cart-footer-right {
  display: flex;
  align-items: center;
}

.selected-count {
  margin-right: 20px;
  font-size: 14px;
}

.highlight {
  color: #409EFF;
  font-weight: bold;
}

.total-price {
  font-size: 16px;
  margin-right: 20px;
}

.total-price .price {
  font-size: 20px;
}

/* 推荐商品 */
.recommended-products {
  margin-top: 30px;
}

.section-title {
  font-size: 20px;
  margin-bottom: 20px;
  color: #333;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
}

.product-item {
  transition: transform 0.3s;
}

.product-item:hover {
  transform: translateY(-5px);
}

.product-card {
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  background-color: #fff;
  border: 1px solid #eee;
  transition: box-shadow 0.3s;
}

.product-card:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.product-img {
  height: 200px;
  overflow: hidden;
}

.product-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.product-card:hover .product-img img {
  transform: scale(1.05);
}

.product-card .product-info {
  padding: 10px;
  min-width: unset;
  flex: unset;
}

.product-card .product-title {
  margin: 0 0 8px;
  font-size: 14px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: text;
}

.product-card .product-price {
  color: #ff4d4f;
  font-weight: bold;
  background: none;
  padding: 0;
  margin: 0;
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .cart-table-header,
  .cart-item {
    grid-template-columns: 60px 350px 120px 120px 120px 80px;
  }
  
  .cart-table-header .item-label {
    padding-left: 60px;
  }
}

@media screen and (max-width: 992px) {
  .cart-table-header,
  .cart-item {
    grid-template-columns: 60px 300px 100px 120px 100px 80px;
  }
  
  .cart-table-header .item-label {
    padding-left: 45px;
  }
}
</style> 